<?php
/**
 * Created by PhpStorm.
 * User: bevan
 * Date: 2018/1/2
 * Time: 下午3:32
 */

namespace thans\auth\model;

use think\facade\Config;
use think\facade\Session;
use think\Model;

class AuthRuleModel extends Model
{
    public function __construct($data = [])
    {
        parent::__construct($data);
        $this->config = Config::get('app.auth');
    }

    public function getRule($name)
    {
        return $this->where('name', 'like', '%' . $name . '%')->find();
    }

    /**
     * 获得权限列表
     * @param integer $uid 用户id
     * @param integer $type
     * @return array
     */
    public function getRuleList($uid, $type)
    {
        static $_authList = []; //保存用户验证通过的权限列表

        $t = implode(',', (array) $type);
        if (isset($_authList[$uid . $t])) {
            return $_authList[$uid . $t];
        }
        if (2 == $this->config['auth_type'] && Session::has('_auth_list_' . $uid . $t)) {
            return Session::get('_auth_list_' . $uid . $t);
        }

        //读取用户所属用户组
        $userModel = new \app\user\model\UserModel();

        $groups = $userModel->getUserGroups($uid);

        $ids = $groups['rules'];

        $ids = explode(',', $ids);

        if (empty($ids)) {
            $_authList[$uid . $t] = [];
            return [];
        }
        $map = array(
            'ar.id'     => $ids,
            'ar.type'   => $type,
            'ar.status' => 1,
        );
        //读取用户组所有权限规则
        $rules = $this
            ->where($map)
            ->alias('ar')
            ->join('menu m', 'm.rule_id = ar.id')
            ->whereIn('m.type', [2, 3])
            ->field('ar.condition,ar.name')
            ->select();
        //循环规则，判断结果。
        $authList = []; //
        foreach ($rules as $rule) {
            if (!empty($rule['condition'])) {
                //根据condition进行验证
                $user    = $userModel->getUserInfo($uid); //获取用户信息,一维数组
                $command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['condition']);
                @(eval('$condition=(' . $command . ');'));
                if ($condition) {
                    $authList[] = strtolower($rule['name']);
                }
            } else {
                //只要存在就记录
                $authList[] = strtolower($rule['name']);
            }
        }
        $_authList[$uid . $t] = $authList;
        if (2 == $this->config['auth_type']) {
            //规则列表结果保存到session
            Session::set('_auth_list_' . $uid . $t, $authList);
        }

        return array_unique($authList);
    }

    /**
     *
     * @method 找到该规格id下的子规格
     * @version
     * @User: bevan
     * @param $id
     * @return
     */
    public function getChild($id)
    {
        return $this->where('pid', $id)->select();
    }
}
